package com.ysd.lis.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * shitianqi
 * 2022-01-18 19:17
 * socket类和请求和方法
 */
@Slf4j
public class WebSocketUtils {


    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    /**
     * 记录当前在线连接数
     */
    public static AtomicInteger onlineCount = new AtomicInteger();

    /**
     * 存放所有在线的客户端
     */
    public static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 上线用户 <br/>
     *
     * @param key
     * @param session
     */
    public static void add(String key, Session session) throws IOException {
        remove(key);
        clients.put(key, session);
        onlineCount.incrementAndGet(); // 在线数加1
        int count = onlineCount.get();
        log.info("有新连接加入：{}，当前在线人数为：{}", key, count > 0? count: 0);
    }


    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 打印某在线用户接收消息内容和在线情况到日志 <br/>
     *
     * @param key
     * @param message
     */
    public static void receive(String key, String message) {
        log.info("服务端收到客户端[{}]的消息:{}", key, message);
//        log.info("当前连接数 = " + clients.size());
    }

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 下线用户 <br/>
     *
     * @param key
     */
    public static void remove(String key) throws IOException {
        if (clients.containsKey(key)) {
            clients.get(key).close();
            clients.remove(key);
            onlineCount.decrementAndGet(); // 在线数减1
//            log.info("有一连接关闭：{}，当前在线人数为：{}", key, onlineCount.get());
        }
//        log.info("当前连接数 = " + clients.size());
    }

    public static void sendAllMessage( MessageTemplate msg) {
//        log.info("当前连接数 = " + clients.size());
        //循环clients
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            //打印消息
            WebSocketUtils.sendMessage(sessionEntry.getKey(), msg);
        }
    }

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 发送消息（内容为对象json） <br/>
     *
     * @param key
     * @param msg
     * @return boolean 是否成功
     */
    public static boolean sendMessage(String key, MessageTemplate msg) {
//        log.info("当前连接数 = " + clients.size());
        if (clients.get(key) == null) {
            return false;
        } else {
            try {
                log.info("发送消息：" + toJsonString(msg));
                clients.get(key).getBasicRemote().sendText(toJsonString(msg));
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    public static String toJsonString(Object obj) {
        ValueFilter filter = new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                if (value instanceof Timestamp) {
                    if(name.equals("sampleda") ){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        return sdf.format((Timestamp) value);
                    }else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        return sdf.format((Timestamp) value);

                    }
                }
                return value;
            }
        };

        return JSON.toJSONString(obj, filter, SerializerFeature.WriteDateUseDateFormat);
    }

}
